package com.class5.springboot.frame.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.class5.springboot.frame.web.exception.RemoteInvokeException;
import com.class5.springboot.frame.web.result.ResultSuccess;
import com.class5.springboot.util.exception.AppException;
import io.jsonwebtoken.Claims;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 所有Controller父类
 * 权限表达式参考：http://blog.csdn.net/zhang89xiao/article/details/60580226
 * @author Administrator
 */
public abstract class SuperRestController extends SuperController{

    //获取全局信息
    protected Claims getClaims(HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("claims");
        return claims;
    }

//    /**
//     * 默认项目Id
//     */
//    protected Long getProjectId(){
//        String apiData = RequestContext.getCurrentContext().getApiData();
//        if(StringUtils.isTrimEmpty(apiData)){
////			throw new ApiException("项目Id不在token中,请更新token");
//            apiData="1";
//        }
//        return Long.valueOf(apiData);
//    }


    /**
     * 返回成功调用的数据
     * @param data
     * @return
     */
    public ResultSuccess successWraper(Object data){
        return new ResultSuccess(data);
    }
    /**
     * 转换异常
     * @param e
     */
    public RuntimeException convertException(Exception e) {
        if(e instanceof RemoteInvokeException) {
            throw (RemoteInvokeException)e;
        }
        if(e instanceof AppException) {
            throw (AppException)e;
        }
        return new AppException("未知服务端异常", e);
    }
    protected String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    protected JSONObject getBodyObject(HttpServletRequest request) {
        try {
            String str = IOUtils.toString(request.getInputStream());

            if(str == null || str.trim().isEmpty()) {
                str = "{}";
            }
            JSONObject obj = JSON.parseObject(str);
            request.setAttribute("_bodyobj", obj);
            return obj;
        } catch (Exception e) {
            throw new AppException("解析body参数失败", e);
        }
    }
}
